# _*_ coding utf-8 _*_
# FILENAME：.py
# DESCRIPTION: 
# AUTH: 
# DATE: 2022/6/1112:52 下午

# DataGrid组件
from PyQt5 import QtCore, QtGui
from PyQt5.QtWidgets import *
from PyQt5.Qt import *
import qtawesome as qta
from sqlalchemy import desc

from components.DataGridComponent import DataGridComponent
from models.baseModel import get_session
from models.factoryModel import FactoryModel
from models.requireSummaryModel import RequireSummaryModel


class DataGrid(DataGridComponent):
    __items = None
    def __init__(self):
        super(DataGrid, self).__init__()
        # 按照行选择，可选择多行
        self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.tableView.setSelectionMode(QAbstractItemView.MultiSelection)
        # 需要初始化设置QItemSelectionModel
        self.targetSelectModel = QItemSelectionModel(self.dataModel)
        self.tableView.setSelectionModel(self.targetSelectModel)
        self.targetSelectModel.selectionChanged.connect(self.OnSelectionChanged)
        self.dataModel.itemChanged.connect(self.OnCheckBoxItemChanged)
        self.setDataModelHeaders()
        self.selectedIds = []
        self.query_click()

    def setDataModelHeaders(self):
        self.dataModel.setHorizontalHeaderLabels(('', '编号', '版本名称', '所属工厂', '创建时间', '更新时间'))
        # 设置列宽
        self.tableView.setColumnWidth(0, 30)
        self.tableView.setColumnWidth(1, 50)
        self.tableView.setColumnWidth(2, 300)
        self.tableView.setColumnWidth(3, 100)
        self.tableView.setColumnWidth(4, 150)
        self.tableView.setColumnWidth(5, 150)
        # self.tableView.horizontalHeader().setHighlightSections(False)
        # self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        # self.tableView.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)
        # self.tableView.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeToContents)

    def OnSelectionChanged(self, selectlist, deselectlist):
        # print('OnSelectionChanged')
        # 选择项改变后，遍历选择的行，将第一列设置为Qt.Checked状态，遍历未选择的行，将未选择的行设置为Qt.Unchecked状态。
        for item in selectlist.indexes():
            rowNum = item.row()
            # 0:Qt.Unchecked, 1:Qt.PartiallyChecked, 2:Qt.Checked
            self.dataModel.item(rowNum, 0).setCheckState(Qt.Checked)

        for item in deselectlist.indexes():
            rowNum = item.row()
            self.dataModel.item(rowNum, 0).setCheckState(Qt.Unchecked)

    def OnCheckBoxItemChanged(self, item):
        # print('OnCheckBoxItemChanged')
        # 对于itemChanged的单元格，获取行的行号和索引，如果该行的checkState为Checked则选择整行，如果checkState为Unchecked，则整行变为不选择。
        rowNum = item.row()
        ModelIndex = self.dataModel.indexFromItem(item)
        if self.dataModel.item(rowNum, 0).checkState() == Qt.Checked:
            self.tableView.selectRow(rowNum)
        elif self.dataModel.item(rowNum, 0).checkState() == Qt.Unchecked:
            self.targetSelectModel.select(ModelIndex, QItemSelectionModel.Deselect | QItemSelectionModel.Rows)

    # 得到记录数，重写
    def getTotalRecordCount(self):
        rowCount = self.query_total()
        # print('rowCount=' + str(rowCount))
        return rowCount

    # 记录查询，重写
    def recordQuery(self, limitIndex):
        self.__items = self.page(limitIndex, self.PageRecordCount, self.edit_no.text(), self.edit_vension.text())
        if len(self.__items) != 0:
            self.dataModel.clear()
            for i in range(len(self.__items)):
                # 添加

                cell = QStandardItem()
                cell.setCheckable(True)
                cell.setEditable(False)
                self.dataModel.setItem(i, 0, cell)

                newItem = QStandardItem(str(self.__items[i][0].id))
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                newItem.setEditable(False)
                self.dataModel.setItem(i, 1, newItem)

                newItem = QStandardItem(str(self.__items[i][0].version_name))
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                newItem.setEditable(False)
                self.dataModel.setItem(i, 2, newItem)

                newItem = QStandardItem(str(self.__items[i][1].name))  # 工厂名称
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                newItem.setEditable(False)
                self.dataModel.setItem(i, 3, newItem)

                newItem = QStandardItem(str(self.__items[i][0].create_date))
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                newItem.setEditable(False)
                self.dataModel.setItem(i, 4, newItem)

                newItem = QStandardItem(str(self.__items[i][0].update_date))
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                newItem.setEditable(False)
                self.dataModel.setItem(i, 5, newItem)

            self.setDataModelHeaders()

    # 重写查询方法
    def query_click(self):
        self.refresh()

    # 分页查询列表
    def page(self, limitIndex=0, pageRecordCount=0, no=0, version=None):
        # 获取dbsession
        session = get_session()
        # 拼接查询
        my_query = session.query(RequireSummaryModel, FactoryModel) \
            .join(FactoryModel, FactoryModel.id == RequireSummaryModel.factory_id)
        my_query = my_query.filter(RequireSummaryModel.is_del == 0)
        # 拼接查询条件
        if version != "":
            my_query = my_query.filter(RequireSummaryModel.version_name.like("%"+version+"%"))
        if no != "":
            my_query = my_query.filter(RequireSummaryModel.id == no)
        # 拼接排序条件
        my_query = my_query.order_by(desc(RequireSummaryModel.update_date))
        # 分页
        my_query = my_query.offset(limitIndex).limit(pageRecordCount)
        # 执行查询
        model = my_query.all()
        session.close()
        return model

    # 查询数据总量
    def query_total(self, version=None, factory=None):
        # 获取dbsession
        session = get_session()
        # 拼接查询
        my_query = session.query(RequireSummaryModel, FactoryModel) \
            .join(FactoryModel, FactoryModel.id == RequireSummaryModel.factory_id)
        my_query = my_query.filter(RequireSummaryModel.is_del == 0)
        # 拼接查询条件
        if version:
            my_query = my_query.filter(RequireSummaryModel.version_name == version)
        if factory:
            my_query = my_query.filter(RequireSummaryModel.factory_id == factory)
        # 执行查询
        count = my_query.count()
        session.close()
        return count
